<?php

namespace app\admin\service\setting;

use app\common\model\setting\Area;
use tmcore\base\BaseService;

/**
 * 区域服务类
 */
class AreaService extends BaseService
{
    /**
     * 区域列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function lists($params)
    {
        // 搜索条件
        $searchParam = [
            '=' => ['pid', 'level'],
            '%like%' => ['name']
        ];
        $where = self::getSearchData($searchParam);
        if(!empty($params['code'])) {
            $pid = Area::where(['code' => $params['code']])->value('id');
            $where[] = ['pid', '=', $pid];
            return Area::where($where)
                ->field('id,pid,level,code,name')
                ->order([ 'id' => 'asc'])
                ->select()
                ->toArray();
        }

        $lists = Area::where($where)
            ->field('id,pid,level,code,name')
            ->order([ 'id' => 'asc'])
            ->select()
            ->toArray();
        return linear_to_tree($lists, 'children');
    }


    /**
     * 添加区域
     * @param array $params
     * @return bool
     */
    public static function add(array $params)
    {
        return Area::add([
            'pid' => $params['pid'],
            'code' => $params['code'] ?? '',
            'name' => $params['name'] ?? '',
            'level' => $params['level'] ?? 0,
        ]);
    }


    /**
     * 编辑区域
     * @param array $params
     * @return bool
     */
    public static function edit(array $params) : bool
    {
        return Area::edit([
            'code' => $params['code'] ?? '',
            'name' => $params['name'] ?? '',
        ], $params['id']);
    }


    /**
     * 删除区域
     * @param array $params
     * @return bool
     */
    public static function delete(array $params)
    {
        return Area::del($params['id']);
    }

    /**
     * 查看区域详情
     * @param $params
     * @return array
     */
    public static function detail($params) : array
    {
        return Area::findOrEmpty($params['id'])->append(['parent_name'])->toArray();
    }

}